import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  Button,
  ScrollView,
  TextInput,
  Alert,
  Platform,
} from 'react-native';
import NfcManager, {Ndef, NfcTech} from 'react-native-nfc-manager';
import {AnimatedCircularProgress} from 'react-native-circular-progress';

const HomeScreen = () => {
  const [supported, setSupported] = useState(false);
  const [enabled, setEnabled] = useState(false);
  const [tag, setTag] = useState(null);
  const [sectors, setSectors] = useState([]);
  const [page, setPage] = useState('4'); // 默认页码为4
  const [data, setData] = useState(''); // 数据输入框
  const [readResult, setReadResult] = useState('');
  const [progress, setProgress] = useState(0);
  const [timer, setTimer] = useState(null);

  const updateAlertMessage = async (
    progress,
    isUnlocking,
    isSelfCheck,
    isReset,
  ) => {
    if (progress >= 100) {
      let successMessage = '';
      if (isSelfCheck) {
        successMessage = '自检成功';
      } else if (isReset) {
        successMessage = '复位成功';
      } else {
        successMessage = isUnlocking ? '开锁成功' : '关锁成功';
      }
      await NfcManager?.setAlertMessageIOS(successMessage);
      if (timer) {
        clearInterval(timer);
      }
      return;
    }

    let progressMessage = `Progress: ${progress}%`;
    if (isSelfCheck) {
      progressMessage = `自检进度: ${progress}%`;
    } else if (isReset) {
      progressMessage = `复位进度: ${progress}%`;
    }
    await NfcManager.setAlertMessageIOS(progressMessage);
  };

  const startProgress = (isUnlocking, isSelfCheck = false, isReset = false) => {
    let currentProgress = 0;
    const intervalId = setInterval(() => {
      if (currentProgress < progress) {
        currentProgress += 1;
        setProgress(currentProgress);
        updateAlertMessage(currentProgress, isUnlocking, isSelfCheck, isReset);
      } else {
        clearInterval(intervalId);
        setTimer(null);
      }
    }, 1); // 每100毫秒更新一次
    setTimer(intervalId);
  };

  useEffect(() => {
    async function initNfc() {
      const isSupported = await NfcManager.isSupported();
      setSupported(isSupported);
      if (isSupported) {
        await NfcManager.start();
        const isEnabled = await NfcManager.isEnabled();
        setEnabled(isEnabled);
      }
    }
    initNfc();

    return () => {
      // NfcManager.setEventListener('NfcManagerDiscoverTag', null);
      // NfcManager.close();
    };
  }, []);

  // 读取NFC标签
  const readNfcTag = async () => {
    try {
      await NfcManager.requestTechnology(NfcTech.Ndef);
      const tag = await NfcManager.getTag();
      setTag(tag);
    } catch (ex) {
      console.warn(ex);
    } finally {
      NfcManager.cancelTechnologyRequest();
    }
  };

  // Android读取所有扇区，ios不支持
  const readAllSectors = async () => {
    try {
      await NfcManager.requestTechnology(NfcTech.NfcA);
      const sectorCount = 16; // 根据NFC标签类型调整扇区数量
      let sectorsData = [];
      for (let i = 0; i < sectorCount; i++) {
        let response;
        response = await NfcManager.transceive([0x30, i]); // 0x30 是MIFARE读扇区命令
        // 格式化数据
        const formattedData = formatData(response);
        sectorsData.push({sector: i, data: formattedData});
      }
      setSectors(sectorsData);
    } catch (ex) {
      console.warn(ex);
      Alert.alert('Error', 'Failed to read sectors');
    } finally {
      NfcManager.cancelTechnologyRequest();
    }
  };

  const formatData = data => {
    return data.map(byte => ('00' + byte.toString(16)).slice(-2)).join(' ');
  };
  // 密码分割
  const convertPassword = password => {
    // 将字符串分割成两个字符一组的数组
    const hexArray = [];
    for (let i = 0; i < password.length; i += 2) {
      hexArray.push(`0x${password.slice(i, i + 2)}`);
    }

    // 如果长度不足4个字节，填充0x00
    while (hexArray.length < 4) {
      hexArray.push('0x00');
    }

    return hexArray;
  };
  async function unlockProcess(isUnlocking) {
    setProgress(0);
    try {
      // 请求一次 NFC 技术
      await NfcManager.requestTechnology(NfcTech.NfcA);

      // 步骤1: 往50扇区写入操作密码
      const operationPassword = [0x88, 0x88, 0x88, 0x88];
      await writePageAndroid(50, operationPassword);
      console.log('-----------------50扇区密码写入成功');
      setProgress(25);

      // 根据状态决定要写入的扇区和数据
      const targetSector = isUnlocking ? 6 : 7;
      const command = isUnlocking
        ? [0x01, 0x03, 0xef, 0x00]
        : [0x02, 0x03, 0xef, 0x00];

      // 步骤2: 写入指令
      await writePageAndroid(targetSector, command);
      console.log(`-----------------${targetSector}扇区指令写入成功`);
      setProgress(50);

      // 步骤3: 等待3秒并读取目标扇区
      await new Promise(resolve => setTimeout(resolve, 3000));
      const result = await readPageAndroid(targetSector);

      // 预期的结果数据
      const expectedResult = isUnlocking
        ? [0x01, 0x03, 0xef, 0x01]
        : [0x02, 0x03, 0xef, 0x01];

      // 比较读取结果与预期结果
      const isSuccess = expectedResult.every(
        (val, index) => val === result[index],
      );

      if (isSuccess) {
        const passwordFromBackend = '666666';
        const formattedPassword = convertPassword(passwordFromBackend);

        // 在NFC写入时，转换为实际的十六进制数字数组
        const hexValues = formattedPassword.map(hexStr => parseInt(hexStr, 16));
        await writePageAndroid(9, hexValues);
        console.log('-----------------9扇区密码写入成功');

        console.log(isUnlocking ? '开锁成功' : '关锁成功');
        setProgress(100);
        Alert.alert(isUnlocking ? '开锁成功' : '关锁成功');
      } else {
        console.log(isUnlocking ? 'Unlock failed' : 'Lock failed');
        Alert.alert(isUnlocking ? '开锁失败' : '关锁失败');
        setProgress(0);
      }
    } catch (ex) {
      console.warn(
        isUnlocking ? 'Unlock process failed:' : 'Lock process failed:',
        ex,
      );
      Alert.alert(isUnlocking ? '开锁失败' : '关锁失败');
      setProgress(0);
    } finally {
      // 确保在操作完成后释放资源
      NfcManager.cancelTechnologyRequest();
    }
  }

  async function writePageAndroid(page, data) {
    try {
      const payload = [0xa2, page, ...data];
      await NfcManager.transceive(payload);
      console.log(`Page ${page} written:`, data);
    } catch (ex) {
      console.warn(ex);
    }
  }

  async function readPageAndroid(page) {
    try {
      const response = await NfcManager.transceive([0x30, page]);
      console.log(`Page ${page} content:`, response);
      return response;
    } catch (ex) {
      console.warn(ex);
    }
  }

  // Android读取特定页
  async function readPage(page) {
    try {
      await NfcManager.requestTechnology(NfcTech.NfcA);
      const response = await NfcManager.transceive([0x30, page]);
      console.log(`Page ${page} content:`, response);
      const formattedData = formatData(response);
      setReadResult(formattedData);
    } catch (ex) {
      console.warn(ex);
    } finally {
      NfcManager.cancelTechnologyRequest();
    }
  }

  // Android写入特定页
  async function writePage(page, data) {
    try {
      await NfcManager.requestTechnology(NfcTech.NfcA);
      const payload = [0xa2, page, ...data];
      await NfcManager.transceive(payload);
      console.log(`Page ${page} written`);
      Alert.alert(`Page ${page} 写入成功`);
    } catch (ex) {
      console.warn(ex);
    } finally {
      NfcManager.cancelTechnologyRequest();
    }
  }

  // ios写入特定页
  const writeIosNfcTag = async (page, data) => {
    try {
      await NfcManager.requestTechnology([
        NfcTech.NfcA,
        NfcTech.Ndef,
        NfcTech.IsoDep,
      ]);

      const tagData = await NfcManager.getTag();

      if (tagData) {
        console.log('Tag found', tagData);

        // 示例命令，根据标签文档调整
        const command = [0xa2, page, ...data]; // 示例写入命令
        const response = await NfcManager.sendMifareCommandIOS(command);
        console.log('Response:', response);
        Alert.alert(`Page ${page} 写入成功`);
      }
    } catch (ex) {
      console.warn(ex);
    } finally {
      NfcManager.cancelTechnologyRequest();
    }
  };

  // iOS 读取特定页
  const readIosNfcPageTag = async page => {
    try {
      await NfcManager.requestTechnology([
        NfcTech.NfcA,
        NfcTech.Ndef,
        NfcTech.IsoDep,
      ]);

      const tagData = await NfcManager.getTag();

      if (tagData) {
        const command = [0x30, page];
        const response = await NfcManager.sendMifareCommandIOS(command);
        await NfcManager?.setAlertMessageIOS('成功开锁。。。。');
        console.log(`Page ${page} content:`, response);
        const formattedData = formatData(response);
        setReadResult(formattedData);
        // const decodedResponse = response
        //   .map(byte => String.fromCharCode(byte))
        //   .join('');
        // console.log('Decoded Response:', decodedResponse);
      }
    } catch (ex) {
      NfcManager.invalidateSessionWithErrorIOS('Failed.');
      console.warn(ex);
    } finally {
      NfcManager.cancelTechnologyRequest();
    }
  };
  async function unlockProcessIOS(isUnlocking) {
    try {
      // 请求一次 NFC 技术
      await NfcManager.requestTechnology([
        NfcTech.NfcA,
        NfcTech.Ndef,
        NfcTech.IsoDep,
      ]);

      // 步骤1: 往50扇区写入操作密码
      const operationPassword = [0x88, 0x88, 0x88, 0x88];
      await writeIosNfcTagForIos(50, operationPassword);
      console.log('-----------------50扇区密码写入成功');
      setProgress(25);
      startProgress(isUnlocking);

      // 根据状态决定要写入的扇区和数据
      const targetSector = isUnlocking ? 6 : 7;
      const command = isUnlocking
        ? [0x01, 0x03, 0xef, 0x00]
        : [0x02, 0x03, 0xef, 0x00];

      // 步骤2: 写入指令
      await writeIosNfcTagForIos(targetSector, command);
      console.log(`-----------------${targetSector}扇区指令写入成功`);
      setProgress(50);

      // 步骤3: 等待3秒并读取目标扇区
      await new Promise(resolve => setTimeout(resolve, 3000));
      const result = await readIosNfcPageTagForIos(targetSector);

      // 预期的结果数据
      const expectedResult = isUnlocking
        ? [0x01, 0x03, 0xef, 0x01]
        : [0x02, 0x03, 0xef, 0x01];

      // 比较读取结果与预期结果
      const isSuccess = expectedResult.every(
        (val, index) => val === result[index],
      );

      if (isSuccess) {
        const nextPassword = [0x66, 0x66, 0x66, 0x66];
        await writeIosNfcTagForIos(9, nextPassword);
        console.log('-----------------9扇区密码写入成功');
        setProgress(100);
        console.log(isUnlocking ? '开锁成功' : '关锁成功');
      } else {
        console.log(isUnlocking ? 'Unlock failed' : 'Lock failed');
        setProgress(0);
        NfcManager.invalidateSessionWithErrorIOS(
          isUnlocking ? '开锁失败.' : '关锁失败.',
        );
      }
    } catch (ex) {
      console.warn(
        isUnlocking ? 'Unlock process failed:' : 'Lock process failed:',
        ex,
      );
      setProgress(0);
      NfcManager.invalidateSessionWithErrorIOS(
        isUnlocking ? '开锁失败.' : '关锁失败.',
      );
    } finally {
      // 确保在操作完成后释放资源
      if (progress >= 100 || !progress) {
        setTimeout(() => {
          NfcManager.cancelTechnologyRequest();
        }, 500);
      }
    }
  }

  const writeIosNfcTagForIos = async (page, data) => {
    try {
      const command = [0xa2, page, ...data]; // 示例写入命令
      const response = await NfcManager.sendMifareCommandIOS(command);
      console.log(`Page ${page} written:`, response);
    } catch (ex) {
      console.warn(ex);
    }
  };

  const readIosNfcPageTagForIos = async page => {
    try {
      const command = [0x30, page];
      const response = await NfcManager.sendMifareCommandIOS(command);
      console.log(`Page ${page} content:`, response);
      return response;
    } catch (ex) {
      console.warn(ex);
    }
  };

  // 自检ios
  const unlockSelfCheckIOS = async () => {
    try {
      await NfcManager.requestTechnology([
        NfcTech.NfcA,
        NfcTech.Ndef,
        NfcTech.IsoDep,
      ]);
      setProgress(25);
      startProgress('', true, false);

      const selfCheckCommand = [0x00, 0x00, 0x00, 0xef];
      await writeIosNfcTagForIos(4, selfCheckCommand);
      console.log('-----------------4扇区自检指令写入成功');
      setProgress(50);
      await new Promise(resolve => setTimeout(resolve, 1500));
      const result = await readIosNfcPageTagForIos(4);
      setProgress(100);
      console.log('自检结果:', result);
      Alert.alert('自检结果:', result.toString());
    } catch (error) {
      setProgress(0);
      NfcManager.invalidateSessionWithErrorIOS('自检失败.');
    } finally {
      // 确保在操作完成后释放资源
      if (progress >= 100 || !progress) {
        setTimeout(() => {
          NfcManager.cancelTechnologyRequest();
        }, 500);
      }
    }
  };
  // 自检安卓
  const unlockSelfCheck = async () => {
    setProgress(0);
    try {
      await NfcManager.requestTechnology(NfcTech.NfcA);
      const selfCheckCommand = [0x00, 0x00, 0x00, 0xef];
      await writePageAndroid(4, selfCheckCommand);
      console.log('-----------------4扇区自检指令写入成功');
      setProgress(50);
      await new Promise(resolve => setTimeout(resolve, 1500));
      const result = await readPageAndroid(4);
      setProgress(100);
      Alert.alert('自检结果:', result.toString());
    } catch (error) {
      Alert.alert('自检失败');
      setProgress(0);
    } finally {
      // 确保在操作完成后释放资源
      NfcManager.cancelTechnologyRequest();
    }
  };

  // 复位ios
  const unlockResetIOS = async () => {
    try {
      await NfcManager.requestTechnology([
        NfcTech.NfcA,
        NfcTech.Ndef,
        NfcTech.IsoDep,
      ]);
      setProgress(25);
      startProgress('', false, true);
      const resetCommand = [0x00, 0x04, 0x04, 0xef];
      await writeIosNfcTagForIos(5, resetCommand);
      console.log('-----------------5扇区复位指令写入成功');
      setProgress(50);
      await new Promise(resolve => setTimeout(resolve, 3000));
      const result = await readIosNfcPageTagForIos(5);

      const expectedResult = [0x00, 0x00, 0x00, 0x00];

      // 比较读取结果与预期结果
      const isResetSuccess = expectedResult.every(
        (val, index) => val === result[index],
      );

      console.log('复位结果:', isResetSuccess ? '成功' : '失败');
      Alert.alert(
        '复位结果:',
        isResetSuccess ? '成功' : '失败' + result.toString(),
      );
      setProgress(100);
    } catch (error) {
      Alert.alert('复位失败');
      setProgress(0);
    } finally {
      // 确保在操作完成后释放资源
      if (progress >= 100 || !progress) {
        setTimeout(() => {
          NfcManager.cancelTechnologyRequest();
        }, 500);
      }
    }
  };

  // 复位安卓
  const unlockReset = async () => {
    setProgress(0);
    try {
      await NfcManager.requestTechnology(NfcTech.NfcA);
      const resetCommand = [0x00, 0x04, 0x04, 0xef];
      await writePageAndroid(5, resetCommand);
      console.log('-----------------5扇区复位指令写入成功');
      setProgress(50);
      await new Promise(resolve => setTimeout(resolve, 3000));
      const result = await readPageAndroid(5);
      const expectedResult = [0x00, 0x00, 0x00, 0x00];
      // 比较读取结果与预期结果
      const isResetSuccess = expectedResult.every(
        (val, index) => val === result[index],
      );
      setProgress(100);
      Alert.alert(
        '复位结果:',
        isResetSuccess ? '成功' : '失败' + result.toString(),
      );
    } catch (error) {
      Alert.alert('复位失败');
      setProgress(0);
    } finally {
      // 确保在操作完成后释放资源
      NfcManager.cancelTechnologyRequest();
    }
  };

  return (
    <View style={{backgroundColor: '#000000'}}>
      <Text style={{color: '#ffffff'}}>
        NFC 是否支持: {supported ? 'Yes' : 'No'}
      </Text>
      <Text style={{color: '#ffffff'}}>
        NFC 已启用: {enabled ? 'Yes' : 'No'}
      </Text>
      <Text style={{color: '#ffffff'}}>
        Tag: {tag ? JSON.stringify(tag) : 'None'}
      </Text>
      <Button
        title="开锁"
        onPress={() =>
          Platform.OS === 'ios' ? unlockProcessIOS(true) : unlockProcess(true)
        }
      />
      <Button
        title="关锁"
        onPress={() =>
          Platform.OS === 'ios' ? unlockProcessIOS(false) : unlockProcess(false)
        }
      />
      <Button
        title="自检"
        onPress={() =>
          Platform.OS === 'ios' ? unlockSelfCheckIOS() : unlockSelfCheck()
        }
      />

      <Button
        title="复位"
        onPress={() =>
          Platform.OS === 'ios' ? unlockResetIOS() : unlockReset()
        }
      />
      <Button title="Read NFC" onPress={readNfcTag} />
      <Button title="Read All" onPress={readAllSectors} />

      <Text style={{color: '#ffffff'}}>读取NFC标签特定页</Text>
      <TextInput
        style={{
          height: 40,
          borderColor: 'gray',
          borderWidth: 1,
          marginVertical: 10,
          color: '#ffffff',
        }}
        placeholder="输入页码"
        value={page}
        onChangeText={setPage}
        keyboardType="numeric"
      />
      <Button
        title="读取页"
        onPress={() =>
          Platform.OS === 'ios'
            ? readIosNfcPageTag(parseInt(page, 10))
            : readPage(parseInt(page, 10))
        }
      />
      <Text style={{color: '#ffffff'}}>读取结果: {readResult.toString()}</Text>

      <Text style={{color: '#ffffff'}}>写入NFC标签特定页</Text>
      <TextInput
        style={{
          height: 40,
          borderColor: 'gray',
          borderWidth: 1,
          marginVertical: 10,
          color: '#ffffff',
        }}
        placeholder="输入数据 (4字节，逗号分隔)"
        value={data}
        onChangeText={setData}
      />
      <Button
        title="写入页"
        onPress={() => {
          const byteArray = data.split(',').map(val => {
            const byte = parseInt(val, 10);
            if (isNaN(byte) || byte < 0 || byte > 255) {
              Alert.alert('Invalid Input', '请确保输入的每个字节在0-255范围内');
              throw new Error('Invalid input');
            }
            return byte;
          });
          if (byteArray.length !== 4) {
            Alert.alert('Invalid Input', '请确保输入4个字节数据');
            return;
          }

          Platform.OS === 'ios'
            ? writeIosNfcTag(parseInt(page, 10), byteArray)
            : writePage(parseInt(page, 10), byteArray);
        }}
      />
      <ScrollView>
        {sectors.map((sector, index) => (
          <View key={index} style={{marginVertical: 10}}>
            <Text>
              Sector {sector.sector}: {sector.data}
            </Text>
          </View>
        ))}
      </ScrollView>

      <AnimatedCircularProgress
        size={120}
        width={15}
        fill={progress}
        tintColor="#00e0ff"
        onAnimationComplete={() => console.log('onAnimationComplete')}
        backgroundColor="#3d5875">
        {fill => <Text style={{color: '#ffffff'}}>{fill?.toFixed(2)}%</Text>}
      </AnimatedCircularProgress>
    </View>
  );
};

export default HomeScreen;
